//
//  DDropIntoViewPresenter.swift
//  Drop
//
//  Created by hushaohua on 2017/12/22.
//  Copyright © 2017年 init. All rights reserved.
//

import UIKit
import CoreData

class DDropIntoTagCell : UICollectionViewCell{
    override init(frame: CGRect) {
        super.init(frame: frame);
        self.contentView.addSubview(self.titleLabel);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var titleLabel:UILabel = {
        var label:UILabel = UILabel(frame:self.bounds);
        label.autoresizingMask = [.flexibleWidth, .flexibleHeight];
        label.numberOfLines = 0;
        label.textColor = UIColor.white;
        label.backgroundColor = UIColor.clear;
        label.layer.borderColor = UIColor.white.cgColor;
        label.layer.borderWidth = 1;
        label.layer.cornerRadius = 3;
        label.textAlignment = .center;
        label.font = UIFont.systemFont(ofSize: 18);
        return label;
    }();
    
//    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
//        print(#function, "\(NSStringFromSelector(action))")
//        let string:String = NSStringFromSelector(action) as String;
//        return string == "customEndTime";
//    }
//    override var canBecomeFirstResponder: Bool{
//        print(#function)
//        return true;
//    }
//
//    override func becomeFirstResponder() -> Bool {
//        print(#function)
//        return true;
//    }
    
    var customEndTimeClosure:((UICollectionViewCell) -> Void)?;
    @objc func customEndTime() -> Void{
        if (self.customEndTimeClosure != nil){
            self.customEndTimeClosure!(self);
        }
    }
}


class DDropIntoViewPresenter: NSObject, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UITextFieldDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.tags.count;
    }
    
    override init() {
        super.init();
    }
    
    var customEndTimeClosure:((Tag) -> Void)?;
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:DDropIntoTagCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DDropIntoTagCell;
        let tag:Tag = self.tags[indexPath.row];
        cell.titleLabel.text = tag.name;
        cell.customEndTimeClosure = {(cell) -> Void in
            self.view?.textField.resignFirstResponder();
            var selectIndexPath = collectionView.indexPath(for: cell);
            if (selectIndexPath != nil && self.customEndTimeClosure != nil){
                let selectedTag:Tag = self.tags[selectIndexPath!.row];
                self.customEndTimeClosure!(selectedTag);
            }
        };
        return cell;
    }
    
    lazy var menuItems:[UIMenuItem] = {
        var items:[UIMenuItem] = [UIMenuItem]();
        let item:UIMenuItem = UIMenuItem(title: "设置结束时间", action: #selector(customEndTime));
        items.append(item);
        return items;
    }();
    @objc func customEndTime() -> Void{
        
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        UIMenuController.shared.menuItems = self.menuItems;
        if (self.updatingDrop == nil){
            return true;
        }else{
            return false;
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        let string:String = NSStringFromSelector(action) as String;
        return string == "customEndTime";
    }

    func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
//        print(#function)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if (self.view != nil){
            var frame = self.view!.textField.frame;
            if (scrollView.contentInset.top + scrollView.contentOffset.y < 0){
                frame.size.height = 44;
                frame.origin.x = 0;
            }else{
                frame.size.height = 0 - scrollView.contentOffset.y - frame.origin.y - 20;
                if (frame.size.height <= 0){
                    frame.size.height = 0;
                }else{
                    frame.origin.x = frame.size.width * (1 - frame.size.height / 44);
                }
            }
            self.view!.textField.frame = frame;
        }
    }
    
    var updatingDrop:Drop?;

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        collectionView.deselectItem(at: indexPath, animated: true);
        
        let tag:Tag = self.tags[indexPath.row];
        if (self.updatingDrop != nil){
            self.updatingDrop?.tag = tag;
            HStoreManager.defaultManger().saveContext();
        }else{
            DDroppingManager.sharedManager().doingDrop?.tag = tag;
            DDroppingManager.sharedManager().finishAndStartNext();
        }
        
        if (self.backClosure != nil){
            self.backClosure!();
        }
    }
    
    var tags:[Tag] = {
        var tags:[Tag] = [Tag]();
        return tags;
    }();
    var originFrame:CGRect?;
    var view:DDropIntoView?{
        didSet{
            self.originFrame = view?.frame;
            view?.collectionView.register(DDropIntoTagCell.self, forCellWithReuseIdentifier: "cell");
            view?.collectionView.delegate = self;
            view?.collectionView.dataSource = self;
            
            self.reloadTags();
            view?.textField.delegate = self;
            NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextDidChanged(_:)), name: Notification.Name.UITextFieldTextDidChange, object: view?.textField);
        }
    }
    
    @objc func textFieldTextDidChanged(_ sender:Notification) -> Void {
        self.searchTag(self.view?.textField.text);
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view?.textField.resignFirstResponder();
        return true;
    }
    
    func reloadTags() -> Void{
        do{
            self.tagsRequest.predicate = nil;
            let tags = try HStoreManager.defaultManger().context.fetch(self.tagsRequest);
//            let count = try HStoreManager.defaultManger().context.count(for: self.tagsRequest);
//            print("tag count:\(count),\(tags.count)")
            let dropInfos = try HStoreManager.defaultManger().context.fetch(self.dropsRequest);
            self.tags.removeAll();
            
            for dropInfo in dropInfos {
                let tagId:NSManagedObjectID = dropInfo.object(forKey: "tag") as! NSManagedObjectID;
                let tag:Tag = HStoreManager.defaultManger().context.object(with: tagId) as! Tag;
                
                self.tags.append(tag);
            }
            for tag in tags {
                if (!self.tags.contains(tag)){
                    self.tags.append(tag);
                }
            }
            
            self.view?.collectionView.reloadData();
        }catch{
            print("drop into get error:\(error)")
        }
    }
    
    func searchTag(_ keyword:String?) -> Void {
        if (keyword == nil || keyword!.count == 0){
            self.reloadTags();
        }else{
            do{
                self.tagsRequest.predicate = self.predicateWith(keyword!);
                let tags = try HStoreManager.defaultManger().context.fetch(self.tagsRequest);
                self.tags.removeAll();
                for tag in tags {
                    self.tags.append(tag);
                }
                self.view?.collectionView.reloadData();
            }catch{
                print("drop into get error:\(error)")
            }
        }
    }
 
    lazy var dropsRequest:NSFetchRequest<NSDictionary> = {
        var request:NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "Drop");
        request.resultType = .dictionaryResultType;
        request.predicate = NSPredicate(format: "tag != nil");
        request.propertiesToFetch = ["tag"];
        request.sortDescriptors = [Drop.defaultSort()];
        request.propertiesToGroupBy = ["tag"];
        return request;
    }();
    
    lazy var tagsRequest:NSFetchRequest<Tag> = {
        var request = Tag.defaultFetchRequest();
        request.includesSubentities = false;
        request.sortDescriptors = [Tag.defaultSort()];
        return request;
    }();
    
    func predicateWith(_ keyword:String) -> NSPredicate {
        let predicate:NSPredicate = NSPredicate(format: "name contains[c] '\(keyword)'");
        return predicate;
    }
    @objc func saveButtonClicked(_ sender:UIButton) -> Void{
        let tag = Tag.newInstance();
        tag.name = (self.view?.textField.text)!;
        DDroppingManager.sharedManager().doingDrop?.tag = tag;
        DDroppingManager.sharedManager().finishAndStartNext();
        if (self.backClosure != nil){
            self.backClosure!();
        }
    }
    var backClosure:(() -> Void)?;
    @objc func undoButtonClicked(_ sender:UIButton) -> Void{
        if (self.backClosure != nil){
            self.backClosure!();
        }
    }
}
